/*
串口通信(4线网口连接硬件) 如pda内置打印机  ANDROIDLINUXMACOSWINDOWS
注意: Android(商米机) 4线串口,如电子秤,也可使用xsdk_flutter_plugin替代

https://pub-web.flutter-io.cn/packages/flutter_libserialport

dependencies:
  flutter_libserialport: ^0.4.0

import 'package:flutter_libserialport/flutter_libserialport.dart';

*/

import 'dart:io';
import 'dart:typed_data';
import 'package:xsdk_flutter/xsdk/framework/base/xsdk_function.dart';
import 'package:xsdk_flutter/xsdk/operation/x_mixin_release.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_flutter.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';

import 'package:flutter_libserialport/flutter_libserialport.dart';

class XSerialApi with XMixinRelease{

  SerialPort? _serialPort;

  XFunctionResultCallback<Uint8List>? callback;

  XSerialApi(
      {
        this.callback,
      }
      );

  //关闭
  @override
  void xRelease() {
    try{
      _serialPort?.close();
      _serialPort?.dispose();
      _serialPort=null;
    }catch(e){
      //
    }
  }

  /*
  扫描可用串口
   */
  List<String> getAvailablePorts(){
    List<String> list;

    if(XFlutterUtils.isiOS()){
      XLogUtils.printLog('---serial port 不支持iOS平台');
      list= [];
    }else{
      list=SerialPort.availablePorts;
    }

    XLogUtils.printLog('---可用串口list= ${XJsonUtils.obj2Json(list)}');

    return list;
  }

  /*
  1.连接
  商米t1: /dev/ttyHSL1
  商米t2: /dev/ttyHSL3
  SPDA(内置打印机):  /dev/ttyHS1
   */
  void connect(
      String serialPort,
      {
        int serialPortMode=SerialPortMode.write,//只写不读
      }
      ) async{

    try{
      if(XFlutterUtils.isiOS()){
        XLogUtils.printLog('---serial port 不支持iOS平台');
        return;
      }

      if(_serialPort!=null){
        xRelease();
      }
      _serialPort = SerialPort(serialPort);
      //注意:这里没有通过授权,则不能读取productId,否则有些设备会报错无法建立连接
      XLogUtils.printLog('---串口信息: name=${_serialPort?.name}');

      bool isOpen=_serialPort?.open(mode: serialPortMode)??false;
      //_serialPort?.openReadWrite()
      //_serialPort?.isOpen

      XLogUtils.printLog('---连接串口:${_serialPort?.name},isOpen=$isOpen');

      if(isOpen){
        if(serialPortMode==SerialPortMode.read || serialPortMode==SerialPortMode.readWrite){
          //读取
          Future((){
            while(_serialPort!=null && _serialPort!.isOpen){
              if(_serialPort?.bytesAvailable!=null && _serialPort?.bytesAvailable!=0){
                Uint8List? data= _serialPort?.read(_serialPort?.bytesAvailable??0);
                if(data!=null){
                  String result=XStringUtils.uint8ListToString_utf8(data);
                  XLogUtils.printLog('---串口读取内容=$result');
                }
              }
              sleep(const Duration(milliseconds: 1000));
            }
            XLogUtils.printLog('---结束串口读取');
          });
        }
      }

    }catch(e){
      XLogUtils.printLog('---serial port connect 报错:${e.toString()}');
    }

  }

  /*
  2.写入
  >0为成功写入
  注意: SPDA内置打印机多个\n无法推纸,则需要使用多行推纸命令: Uint8List.fromList([27,100,n])
   */
  int? write(Uint8List bytes){

    int? res=null;

    if(_serialPort!=null && _serialPort!.isOpen){
      res = _serialPort?.write(bytes);
      //_serialPort?.flush();
    }

    return res;
  }

}
